package edu.byui.chat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread extends Thread {
	private ObjectInputStream fromClient;
	private ObjectOutputStream toClient;
	private Socket sock;
	private Chat chat;
	private String fileLocation;

	public ServerThread(Socket receivedSocket, Chat c, String fl) {
		this.chat = c;
		this.fileLocation = fl;
		this.sock = receivedSocket;
		try {
			this.fromClient = new ObjectInputStream(receivedSocket.getInputStream());
			this.toClient = new ObjectOutputStream(receivedSocket.getOutputStream());
		}
		catch (Exception e) {
			System.out.println("THREAD ERROR");
			e.printStackTrace();
		}
		System.out.println(receivedSocket.toString());
	}

	@SuppressWarnings("unchecked")
	public void run() {		
		while (!this.sock.isClosed()) {
			try {
				Command command = (Command) fromClient.readObject();
				String header = command.getHeader();
				String username = command.getUsername();
				if (header.equals("close") && username.equals("root")) {
					System.out.println("Shutdown request received...\nSaving Session...");
					chat.save(this.fileLocation);
					System.out.println("[Server Shutdown]");
					System.exit(1);
					break;
				}
				else if (header.equals("logout")) {
					//					toClient.close();
					//					fromClient.close();
					break;
				}
				else {
					ArrayList params = new ArrayList(0);
					params.add(0, command);
					params.add(1, this.chat);
					params.add(2, this.toClient);
					AppController.handleRequest(params);
				}
			}
			catch(IOException e) {
				System.out.println("There was an IO Exception in the THREAD when a Client tried to connect!");
				System.out.println("Here is the Stack Trace:");
				e.printStackTrace();
				break;
			}
			catch(SecurityException e) {
				System.out.println("There was a Security Exception in the THREAD when a Client tried to connect!");
				System.out.println("Here is the Stack Trace:");
				e.printStackTrace();
				break;
			}
			catch(Exception e){
				System.out.println("The following error has occurred in the THREAD with the Server:");
				e.printStackTrace();
				break;
			}
		}
	}
}
